<template>
    <div>
      <span style="color: red; text-align: center;">角色分配菜单</span>
      <div class="common-layout" style=" margin: 0 30%;">
        <div>
          <el-container>
            <el-aside width="200px">
              角色
              <!-- 使用 el-tree 组件展示树形数据 -->
              <el-tree :data="RoleModel" :highlight-current="true" ref="treeRef" :props="treePropsRole" node-key="roleId"
                @node-click="handleNodeClickRole">
              </el-tree>
              <!-- 显示点击节点的 roleId -->
              <!-- <div v-if="AddModel.roleId">你点击的节点的 roleId 是: {{ AddModel.roleId }}</div> -->
            </el-aside>
            <el-aside width="200px">
              <div>
                <!-- 使用 el-tree 组件 -->
                <el-tree :data="treeData" :default-checked-keys="AddModel.menuId" show-checkbox node-key="menuId"
                  :props="defaultPropsMenu" @check-change="handleCheckChange" ref="treeRef"
                  :default-expand-all="true"></el-tree>
              </div>
            </el-aside>
          </el-container>
        </div>
        <div>
          <el-button type="success" @click="AddRoleMenu" >保存</el-button>
        </div>
      </div>
    </div>


  </template>
  
  <script setup lang="ts">
  //#region import
  import { ElMessage, ElMessageBox } from 'element-plus';
  import { compile, computed, nextTick, onMounted, reactive, ref } from 'vue'
  import { useRouter, useRoute } from 'vue-router';
  import { useCounterStore } from '@/stores/counter';
  import DepData from '@/stores/departmentData'
  import axios from 'axios';
  import { ElTree } from 'element-plus';
  import type { AnyColumn } from 'element-plus/es/components/table-v2/src/common.mjs';
  import {read,write} from '@/axios/axiosHelper'
  //pini保存
  const store = useCounterStore();
  //跳转
  const router = useRouter();
  
  //#endregion
  
  //#region  获取角色数据(id,名称)
  
  //获取角色的数据
  const RoleModel = ref([])
  //角色分页所需数据
const page=reactive({
    pageindex:1,
    pagesize:100,
    totalcount:0,
    totalpage:0,
})
  //获取角色数据(id, 名称)
  const GetRole = () => {
    read.get("/read/api/Message/GetRoleName",{
        params:{
            Pageindex:page.pageindex,
            Pagesize:page.pagesize
        }
    }).then(res => {
      RoleModel.value = res.data.list;
      console.log(RoleModel.value, "角色名称")
    })
  }
  
  // 定义树的属性配置
  const treePropsRole: any = ref({
    label: 'roleName', // 指定节点的标签显示字段为 roleName
    children: [] // 指定子节点字段为 children
  });
  
  // 处理节点点击事件(通过roleId 查询 菜单数据实现反填)
  const handleNodeClickRole = (data: any) => {
    //清空节点
    AddModel.menuId = [];
    AddModel.roleId = data.roleId;
    read.get(`/read/api/Message/QueryRoleByMenue?RoleId=${data.roleId}`).then(res => {
      AddModel.menuId = res.data.data.map((item: any) => item.menuId)
      console.log(res.data.data, '反填菜单名称res')
      console.log(AddModel.menuId, '反填菜单名称')
      nextTick()
      // 强制更新 el-tree 的选中状态
      treeRef.value.setCheckedKeys(AddModel.menuId);
    })
  };
  
  //#endregion
  
  
  //#region  获取菜单数据(id,名称)
  
  //获取菜单的数据
  const MenuModel = ref([])
  // 存储树形结构的数据
  const treeData = ref([]);
  //获取菜单数据(id, 名称)
  const GetMenu = () => {
    read.get("/read/api/Message/QueryMenuName2").then(res => {
      MenuModel.value = res.data.data
      console.log(MenuModel.value, "赋值MenuModel.value")
      console.log(res.data.data, "获取res.data.data")
      treeData.value = convertToTree(MenuModel.value)
      console.log(treeData.value, "获取树形菜单")
    })
  }
  
  // 将普通数组转换为树形结构
  const convertToTree = (data: any) => {
    const tree: any = [];
    const map: any = {};
  
    // 先将每个节点存储到 map 中
    data.forEach((item: any) => {
      map[item.menuId] = { ...item, children: [] };
    });
  
    // 再根据 parentId 构建树形结构
    data.forEach((item: any) => {
      if (item.pId === 0) {
        tree.push(map[item.menuId]);
      } else {
        const parent = map[item.pId];
        if (parent) {
          parent.children.push(map[item.menuId]);
        }
      }
    });
    return tree;
  };
  
  // 获取 el-tree 组件的引用
  const treeRef = ref<InstanceType<typeof ElTree>>();
  
  // 定义 tree 组件的属性配置
  const defaultPropsMenu = {
  children: 'children',
  label: 'menuName',
  menuId:'',
  };
  
  // 存储选中节点的 id 数组
  const checkedIds: any = ref([]);
  
  //获取菜单多选值
  const handleCheckChange = () => {
    AddModel.menuId = treeRef.value?.getCheckedKeys() || [];
    console.log(AddModel.menuId, '获取单个选中值')
  };
  
  
  const AddModel: any = reactive({
    "roleId": 0,
    "menuId": []
  })
  
  
  //#endregion
  
  //#region 添加
  
  
  const AddRoleMenu = () => {
    if (AddModel.roleId == "") {
      ElMessage.error("请选择角色")
      return;
    }
    console.log(AddModel.menuId)
    console.log(AddModel.roleId)
    write.post("/write/api/Message/AddRoleMenu", AddModel).then(res => {
      if (res.data.code == 212) {
        ElMessage.success(res.data.msg)
      }
    })
  }
  
  //#endregion
  
  
  
  onMounted(() => {
    GetRole()
    GetMenu()
  })
  
  
  
  
  
  </script>
  
  <style scoped></style>